package com.yipinhouse.signing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yipinhouse.common.enums.HouseTypeEnum;
import com.yipinhouse.common.exception.HouseException;
import com.yipinhouse.employee.client.BrokerInfoQueryClient;
import com.yipinhouse.employee.client.result.BrokerInfoResult;
import com.yipinhouse.house.client.*;
import com.yipinhouse.house.client.result.NewHouseResultInfo;
import com.yipinhouse.house.client.result.ResoldApartmentInfoResult;
import com.yipinhouse.house.client.result.ResoldHousingResult;
import com.yipinhouse.signing.common.IntentionMoneyStatusEnum;
import com.yipinhouse.signing.common.SigningResultCode;
import com.yipinhouse.signing.common.enums.EstateTypeEnum;
import com.yipinhouse.signing.common.enums.SellerTypeEnums;
import com.yipinhouse.signing.infra.model.Contract;
import com.yipinhouse.signing.infra.model.HouseTrade;
import com.yipinhouse.signing.infra.model.IntentionMoney;
import com.yipinhouse.signing.infra.model.Signing;
import com.yipinhouse.signing.infra.mapper.SigningMapper;
import com.yipinhouse.signing.service.ContractService;
import com.yipinhouse.signing.service.HouseTradeService;
import com.yipinhouse.signing.service.IntentionMoneyService;
import com.yipinhouse.signing.service.SigningService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yipinhouse.signing.service.dto.HouseTradeDto;
import com.yipinhouse.signing.service.param.DoSigningServiceParam;
import com.yipinhouse.user.client.UserQueryClient;
import io.seata.spring.annotation.GlobalTransactional;
import jodd.bean.BeanTemplateParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 签约表 服务实现类
 * </p>
 *
 * @author WangCong
 * @since 2022-12-01
 */
@Service
@Slf4j
public class SigningServiceImpl extends ServiceImpl<SigningMapper, Signing> implements SigningService {
    @Resource
    private ContractService contractService;

    @Resource
    private UserQueryClient userQueryClient;

    @Resource
    private BrokerInfoQueryClient brokerInfoQueryClient;

    @Resource
    private NewHouseQueryClient newHouseQueryClient;

    @Resource
    private ResoldApartmentManageClient resoldApartmentManageClient;

    @Resource
    private ResoldHouseManageClient resoldHouseManageClient;

    @Resource
    private ResoldApartmentQueryClient resoldApartmentQueryClient;

    @Resource
    private ResoldHouseQueryClient resoldHouseQueryClient;

    @Resource
    private HouseTradeService houseTradeService;

    @Resource
    private IntentionMoneyService intentionMoneyService;

    @Override
    @GlobalTransactional
    public void doSigning(DoSigningServiceParam param) {
        log.info("service:签约：参数:{}", param);

        String newHouse = HouseTypeEnum.NEW_HOUSE.getCode();
        String rent = HouseTypeEnum.RENTAL_HOUSING.getCode();
        String resold = HouseTypeEnum.SECOND_HAND_HOUSING.getCode();

//        查询合同是否存在
        Contract contract = contractService.getById(param.getContractId());
        if (contract == null)
            throw new HouseException(SigningResultCode.CONTRACT_NOT_EXISTS);


//TODO        设置成交价格 折扣

//        获取房源信息
        String houseType = contract.getHouseType();
        NewHouseResultInfo newHose = null;
        ResoldApartmentInfoResult apartment = null;
        ResoldHousingResult rentHouse = null;

        if (houseType.equals(newHouse))
            newHose = newHouseQueryClient.searchNewHouseById(contract.getHouseId()).getData();
        else if (houseType.equals(resold))
            apartment = resoldApartmentQueryClient.getResoldApartmentInfo(contract.getHouseId()).getData();
        else if (houseType.equals(rent))
            rentHouse = resoldHouseQueryClient.getResoldHouseInfo(contract.getHouseId()).getData();


//        TODO 生成房屋售卖记录
        HouseTrade trade = new HouseTrade();

        //设置小区id 与类型
        Integer estateId = null;
        String estateType = EstateTypeEnum.ESTATE.getCode();
        BigDecimal price = null;
        if (houseType.equals(newHouse)) {
            estateId = newHose.getBuildingId();
            trade.setEstateType(EstateTypeEnum.BUILDING.getCode());
            price = newHose.getSinglePrice();
        } else if (houseType.equals(resold)) {
            estateId = apartment.getEstateId();
            price = apartment.getPrice();
        }
        else if (houseType.equals(rent)) {
            estateId = rentHouse.getEstateId();
            price = rentHouse.getRent();
        }

        trade.setEstateId(estateId);
        trade.setEstateType(estateType);

//        设置房源id
        trade.setHouseId(contract.getHouseId());
//        设置房源类型
        trade.setHouseType(contract.getHouseType());
//        设置经纪人
        trade.setBrokerId(contract.getBrokerId());
//        设置用户id
        trade.setCustomerId(contract.getUserId());
//      设置业主id
        if (contract.getSellerType().equals(SellerTypeEnums.USER.getCode()))
            trade.setOwnerId(contract.getSellerId());
//        设置门店id
        //        获取门店id
        BrokerInfoResult brokerInfo = brokerInfoQueryClient.getBrokerInfo(contract.getBrokerId()).getData();
        Integer shopId = brokerInfo.getShopId();
        trade.setShopId(shopId);
//        设置交易类型
        trade.setTradeType(contract.getContractType());
//        设置成交价
        trade.setTradePrice(contract.getTradePrice());
//        设置单价
        trade.setUnitPrice(price);
//        设置交易时间
        trade.setTradeTime(DateUtil.now());
//        设置首付
        trade.setDownPayment(contract.getDownPayment());
//        设置合同id
        trade.setContractId(contract.getId());

        houseTradeService.save(trade);

        //        购买房源
        if (houseType.equals(newHouse))
            newHouseQueryClient.saleHouse(contract.getHouseId());
        else if (houseType.equals(resold))
            resoldApartmentManageClient.saleHouse(contract.getHouseId());
        else if (houseType.equals(rent))
            resoldHouseManageClient.saleHouse(contract.getHouseId());

//        TODO 修改意向金状态
        IntentionMoney intentionMoney = intentionMoneyService.getOne(new QueryWrapper<IntentionMoney>()
                .eq("id", contract.getIntentionId())
                .eq("status", IntentionMoneyStatusEnum.PAID.getCode()));

        if (intentionMoney==null)
            throw new HouseException(SigningResultCode.INTENTION_NOT_EXISTS);

        intentionMoney.setStatus(IntentionMoneyStatusEnum.FINISH.getCode());
        intentionMoneyService.updateById(intentionMoney);


//TODO   下架房源
        if (houseType.equals(resold))
            resoldApartmentManageClient.pullOffShelf(contract.getHouseId());
        else if (houseType.equals(rent))
            resoldHouseManageClient.pullOffShelf(contract.getHouseId());

    }

    /**
     * 根据用户id获取房源交易记录
     * @param userId
     * @return
     */
    @Override
    public List<HouseTradeDto> getHouseTradeByUser(Integer userId) {
        List<HouseTrade> houseTrades = houseTradeService.list(new QueryWrapper<HouseTrade>()
                .eq("customer_id", userId));

        if (houseTrades==null||houseTrades.size()<1)
            return  null;

        List<HouseTradeDto> houseTradeDtos = BeanUtil.copyToList(houseTrades, HouseTradeDto.class);
        return houseTradeDtos;
    }

    /**
     * 根据id获取房源交易记录
     * @param houseTradeId
     * @return
     */
    @Override
    public HouseTradeDto getHouseTradeById(Integer houseTradeId) {
        HouseTrade houseTrade = houseTradeService.getById(houseTradeId);
        HouseTradeDto dto = BeanUtil.toBean(houseTrade, HouseTradeDto.class);
        return dto;
    }
}
